<?php

namespace App\Http\Controllers\VideoApi;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use App\Models\video\BroadcasterModel;
use App\Models\video\BroadcasterRelationModel;
use App\Models\video\CommentModel;
use App\Models\video\CourseCatalogModel;
use App\Models\video\CourseModel;
use App\Models\video\DynamicModel;
use App\Models\video\OperateModeModel;
use App\Models\video\ReplyModel;
use App\Models\video\SubscribeLibraryModel;
use App\Models\video\SubscriptionModel;
use App\Models\video\VideoSettingModel;
use App\Models\video\VideoUserModel;
use App\Models\video\VodVideoModel;
use App\Models\video\WxServer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class DynamicController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->noCheckTokenAction = ['getDynamicList', "getDynamicDetail"]; //不校验openid
        parent::__construct($request);
    }

    // 获取动态列表
    public function getDynamicList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 10;
        $sortName = $request->sortName ? Str::snake($request->sortName) : "create_time";
        $sortOrder = $request->sortOrder ?: "desc";
        $filter = [["d.mall_id", '=', $request->mallData["id"]], ["d.status", '=', 1]];
        $request->token && $userId = $this->getTokenVar($request->token, "id");
        $settingData = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]]);
        $db = DynamicModel::from(DynamicModel::query()->getModel()->getTable()." as d")
            ->leftJoin(VodVideoModel::query()->getModel()->getTable()." as v", "v.id", "=", "d.belong_id");
        if($settingData["operateMode"] == '1'){
            $temp = BroadcasterModel::getFields("id", ["status" => 1, "mall_id" => request()->mallData["id"]], true, false);
            if(!empty($temp["id"]))
                $filter[] = ["d.broadcaster_id", "=", $temp["id"]];
        }elseif(!empty($userId)){
            $subData = SubscriptionModel::getFields("broadcaster_id", ["user_id" => $userId], false, false);
            $selectId = [];
            foreach ($subData as $value) {
                $selectId[] = $value["broadcasterId"];
            }
            $db->whereIn("d.broadcaster_id", $selectId);
        }
        $db->where($filter);
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$pageSize);
        $data["list"] = [];
        $database = $db->select([
            "d.id","d.broadcaster_id","d.belong_id","d.contents","d.pic_id","d.praise_num","d.type","d.create_time","d.share_count","d.page_view",
            "v.title","v.view_count","v.cover_img_id","v.video_length", "v.type as videoType", "v.file_type"
        ])->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy("d.".$sortName, $sortOrder)->get();
        if($database){
            $database = UpTools::transferFields($database->toArray());
            foreach ($database as $k => $item){
                $data["list"][$k] = [
                    "id" => $item["id"], "contents" => $item["contents"], "praiseNum" => $item["praiseNum"], "type" => $item["type"], "publishTime" => UpTools::handleTimeToText($item["createTime"]),
                    "broadcasterId" => $item["broadcasterId"], "shareCount" => $item["shareCount"], "pageView" => $item["pageView"]
                ];
                if(empty($userTempData[$item["broadcasterId"]])){
                    $userTempData[$item["broadcasterId"]] = BroadcasterModel::getFields("name,avatar_id", ["id" => $item["broadcasterId"]]);
                    if(!empty($userId))
                        $userTempData[$item["broadcasterId"]]["is"] = BroadcasterRelationModel::getCount(["broadcaster_id" => $item["broadcasterId"], "user_id" => $userId]);
                }
                $data["list"][$k]["userName"] = !empty($userTempData[$item["broadcasterId"]]["name"]) ? $userTempData[$item["broadcasterId"]]["name"] : "";
                $data["list"][$k]["userAvatar"] = !empty($userTempData[$item["broadcasterId"]]["avatarUrl"]) ? $userTempData[$item["broadcasterId"]]["avatarUrl"] : "";
                if($item["type"] == '2'){ // 2视频
                    $data["list"][$k] = array_merge($data["list"][$k], [
                        "videoId" => $item["belongId"], "videoTitle" => $item["title"], "videoLength" => $item["videoLength"],
                        "viewCount" => $item["viewCount"], "coverImgUrl" => UpTools::processingPictures($item["coverImgId"]),
                        "fileType" => $item["fileType"]
                    ]);
                    if($item["videoType"] == "2"){ // 是课程
                        $catalog = CourseCatalogModel::getFields("course_id", ["video_id" => $item["belongId"]], true, false);
                        if(empty($courseData[$catalog["courseId"]])){
                            $subSql = CourseCatalogModel::query()->whereRaw("course_id = ".CourseModel::query()->getModel()->getTable().".id and status = '1'")
                                ->selectRaw("count(*)")->toSql();
                            try {
                                $courseData[$catalog["courseId"]] = CourseModel::query()->select("id", "name", "number")
                                    ->selectRaw("({$subSql}) as currentNum")
                                    ->where("id", $catalog["courseId"])
                                    ->first()->toArray();
                            }catch (\Exception $e){
                                $courseData[$catalog["courseId"]] = [];
                            }
                        }
                        $data["list"][$k]["type"] = 3; // 代表课程
                        $data["list"][$k]["courseInfo"] = $courseData[$catalog["courseId"]];
                    }
                }else{ // 图文
                    if(!empty($item["picId"])) {
                        if (strpos($item["picId"], ",") !== false) {
                            $data["list"][$k]["picUrl"] = explode(",", $item["picId"]);
                            foreach ($data["list"][$k]["picUrl"] as &$i) {
                                $i = UpTools::processingPictures($i);
                            }
                        } else {
                            $data["list"][$k]["picUrl"][] = UpTools::processingPictures($item["picId"]);
                        }
                    }
                }
                $data["list"][$k]["userPraiseStatus"] = 0;
                $data["list"][$k]["deleteStatus"] = 0;
                if(!empty($userId)){
                    $item["userPraiseStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $item["id"], "type" => 3, "mode" => 1]);
                    if(!empty($userTempData[$item["broadcasterId"]]["is"])){
                        $data["list"][$k]["deleteStatus"] = 1;
                    }
                }
                $data["list"][$k]["commentCount"] = CommentModel::getCount(["belong_id" => $item["id"], "type" => 3, "status" => 1, "mall_id" => $request->mallData["id"]]) +
                    ReplyModel::query()->from(ReplyModel::query()->getModel()->getTable(). " as r")
                        ->leftJoin(CommentModel::query()->getModel()->getTable()." as c", "c.id", '=', "r.comment_id")
                        ->where(["c.belong_id" => $item["id"], "r.status" => 1])
                        ->count();
            }
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 动态详情
    public function getDynamicDetail(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "动态ID"));
        }
        $data = DynamicModel::from(DynamicModel::query()->getModel()->getTable()." as d")
            ->leftJoin(VodVideoModel::query()->getModel()->getTable()." as v", "v.id", "=", "d.belong_id")->select([
                "d.id","d.broadcaster_id","d.belong_id","d.contents","d.pic_id","d.praise_num","d.type","d.create_time","d.share_count","d.page_view",
                "v.title","v.view_count","v.cover_img_id","v.video_length", "v.type as videoType", "v.file_type"
            ])->where(["d.id" => $request->id])->first()->toArray();
        if(!empty($data)){
            $data = UpTools::transferFields($data);
            $data["userPraiseStatus"] = 0;
            if($request->token && $userId = $this->getTokenVar($request->token, "id")) {
                DynamicModel::doUpdate(["page_view" => DB::raw("page_view+1")], ["id" => $request->id]);
                $data["pageView"] ++;
                $data["userPraiseStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $data["id"], "type" => 3, "mode" => 1]);
            }
            $userData = BroadcasterModel::getFields("name,avatar_id", ["id" => $data["broadcasterId"]]);
            $this->returnData["data"] = [
                "id" => $data["id"], "contents" => $data["contents"], "praiseNum" => $data["praiseNum"], "type" => $data["type"], "publishTime" => UpTools::handleTimeToText($data["createTime"]),
                "broadcasterId" => $data["broadcasterId"], "userName" => $userData["name"], "userAvatar" => $userData["avatarUrl"], "pageView" => $data["pageView"], "userPraiseStatus" => $data["userPraiseStatus"]
            ];
            if($data["type"] == '2'){ // 视频
                $this->returnData["data"] = array_merge($this->returnData["data"], [
                    "videoId" => $data["belongId"], "videoTitle" => $data["title"], "viewCount" => $data["viewCount"],
                    "videoLength" => $data["videoLength"], "coverImgUrl" => UpTools::processingPictures($data["coverImgId"]),
                    "fileType" => $data["fileType"]
                ]);
                if($data["videoType"] == "2"){ // 是课程
                    $catalog = CourseCatalogModel::getFields("course_id", ["video_id" => $data["belongId"]], true, false);
                    $subSql = CourseCatalogModel::query()->whereRaw("course_id = ".CourseModel::query()->getModel()->getTable().".id and status = '1'")
                        ->selectRaw("count(*)")->toSql();
                    try {
                        $this->returnData["data"]["courseInfo"] = CourseModel::query()->select("id", "name", "number")
                            ->selectRaw("({$subSql}) as currentNum")
                            ->where("id", $catalog["courseId"])
                            ->first()->toArray();
                    }catch (\Exception $e){
                        $this->returnData["data"]["courseInfo"] = [];
                    }
                    $this->returnData["data"]["type"] = 3; // 代表课程
                }
            }else{ // 图文
                if(strpos($data["picId"], ",") !== false){
                    $this->returnData["data"]["picUrl"] = explode(",", $data["picId"]);
                    foreach ($this->returnData["data"]["picUrl"] as &$i){
                        $i = UpTools::processingPictures($i);
                    }
                }else{
                    $this->returnData["data"]["picUrl"][] = UpTools::processingPictures($data["picId"]);
                }
            }
            $this->returnData["data"]["commentCount"] = CommentModel::getCount(["belong_id" => $data["id"], "type" => 3, "status" => 1, "mall_id" => $request->mallData["id"]]) +
                ReplyModel::from(ReplyModel::query()->getModel()->getTable(). " as r")
                    ->leftJoin(CommentModel::query()->getModel()->getTable()." as c", "c.id", '=', "r.comment_id")
                    ->where(["c.belong_id" => $data["id"], "r.status" => 1])
                    ->count();
        }
        return $this->return_result($this->returnData);
    }

    // 发表动态
    public function publishDynamic(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->contents && !$request->picId){
            return $this->return_result(ErrorCode::code("customized", "数据不能为空"));
        }
        $data = BroadcasterRelationModel::getFields("broadcaster_id", ["user_id" => $request->userLoginData["id"]], true, false);
        DynamicModel::toAdd([
            "broadcaster_id" => $data["broadcasterId"], "contents" => $request->contents, "pic_id" => $request->picId, "type" => 1, "status" => 1
        ]);
        $userSubscribe = SubscriptionModel::from(SubscriptionModel::query()->getModel()->getTable()." as s")
            ->leftJoin(VideoUserModel::query()->getModel()->getTable()." as u", "u.id", "=", "s.user_id")
            ->select("u.openid", "s.create_time")
            ->where(["s.broadcaster_id" => $data["broadcasterId"], "s.remind_status" => 1])
            ->get()->toArray(); // 查询授权接受订阅消息提醒的用户
        if(!empty($userSubscribe)){
            $templateData = [
                "thing1" => ["value" => "UP主发布图文动态了"],
                'thing4' => ["value" => "{$request->contents}"],
                "thing2" => ["value" => "赶紧去围观吧！"]
            ];
            $template_id = SubscribeLibraryModel::query()
                ->where("type", SubscribeLibraryModel::DYNAMIC_REMIND)
                ->where("mall_id", $request->mallData["id"])
                ->value("template_id");
            foreach ($userSubscribe as $item){
                $templateData['time5'] = ["value" => date("Y年m月d日 H:i", $item['create_time'])];
                WxServer::getInstance()->sendTplNotice($item["openid"], $template_id, $templateData);
                UpTools::writeLog("{$item["openid"]} 发了：".var_export($templateData, true), "publishDynamic.txt");
            }
        }
        return $this->return_result($this->returnData);
    }

    // 赞
    public function toPraiseDynamic(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "评论ID"));
        }
        if (empty(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 3, "mode" => 1]))) { // 没赞
            OperateModeModel::toAdd(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 3, "mode" => 1]);
        } else {
            OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 3, "mode" => 1]);
        }
        DynamicModel::doUpdate(["praise_num" => OperateModeModel::getCount(["belong_id" => $request->id, "type" => 3, "mode" => 1])], ["id" => $request->id]);
        return $this->return_result($this->returnData);
    }

    // 删除动态
    public function delDynamic(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        DynamicModel::delByFilter(["id" => $request->id]);
        return $this->return_result($this->returnData);
    }
}
